import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/views/base/EditChildParmRule.dart';
import 'package:yuellyfactory/views/dto/PriceMaterial.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';

class MaterialListEditVC extends StatefulWidget {

  final PricePart pricePart;
  final PriceMaterial priceMaterial;

  final VoidCallback callback;
  const MaterialListEditVC({super.key, required this.pricePart, required this.callback, required this.priceMaterial});

  @override
  State<MaterialListEditVC> createState() => _MaterialListEditVCState();
}

class _MaterialListEditVCState extends State<MaterialListEditVC> {
  
  Map<String,dynamic> values={};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    for(PriceParm parm in widget.pricePart.childParmList){
      if(parm.value.isNotEmpty){
        values[parm.id]=parm.value;
      }
    }
    if(widget.priceMaterial.data.isNotEmpty){
      List<dynamic> list = json.decode(widget.priceMaterial.data);
      for(var item in list){
        var id=item["id"];
        var value=item["value"];
        var rule=item["rule"];
        var handle=item["handle"];
        debugPrint("$id===$value");
        if(rule!=null&&rule.toString().contains("[")){
          values[id]=rule;
        }else{
          if(handle==0){
            values[id]=value;
          }

        }


      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),
      title: Row(
        children: [
          const  Text("零件编辑(红色框必填，蓝色框为输入项)"),
          const SizedBox(width: 50,),
          ViewUtil.doneIcon("保存", (){
            save();
          })
        ],
      ),


      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wrap(
            crossAxisAlignment: WrapCrossAlignment.start,
            runAlignment: WrapAlignment.start,
            direction: Axis.horizontal, // 水平方向排列（默认）
            alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
            spacing: 10, // 子组件横向间距
            runSpacing: 0, // 换行后纵向间距
            children: paramView(),
          ),

          const SizedBox(height: 16),

        ],
      ),

    );
  }

  List<Widget> paramView(){
    List<Widget> widgets=[];
    for(PriceParm parm in widget.pricePart.childParmList){
      widgets.add(SizedBox(width: 230,
        child:parm.handle==0?
        ShadInput(
          decoration: ShadDecoration(
            border: ShadBorder.all(color: parm.required==1?Colors.red:Colors.blue ),
          ),
          prefix: Text(parm.name),
          suffix: Text(parm.unit??""),
          textAlign: TextAlign.end,
          placeholder: Text("请输入${parm.name}"),
          enabled: parm.handle==0,
          initialValue: parm.handle==0? getParmValue(parm.id):getRuleString(parm.rule),
          onChanged: (value){
            debugPrint(value);
            parm.value=value;
            values[parm.id]=value;
          },
        )
            :
        GestureDetector(onTap: (){

          PriceParm priceParm=PriceParm();
          priceParm.id=parm.id;
          if(values.containsKey(parm.id)){
            priceParm.rule=values[parm.id];
          }else{
            priceParm.rule=parm.rule;
          }
          showShadSheet(
            barrierColor: Colors.transparent,
            side: ShadSheetSide.right,
            context: context,
            builder: (context) =>   EditChildParmRule(priceParm: priceParm,pricePart: widget.pricePart,callback: (selectValue){
            //  parm.rule=selectValue;
              values[parm.id]=selectValue;
              setState(() {

              });
            },),
          );
        },child: Container(
          alignment: Alignment.centerLeft,
          height: 40,
          margin: EdgeInsets.only(top: 3,left: 5,right: 5),
          padding: EdgeInsets.symmetric(horizontal: ViewUtil.screenWidth(20) ),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: 2),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Text("${parm.name}:"+getRuleString(values.containsKey(parm.id)?values[parm.id]:parm.rule)),
        ),

        )
      )
      );
    }
    return widgets;
  }

  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      debugPrint(rule);
      if(rule.toString().contains("[")){
        List<dynamic> list = json.decode(rule);
        for(var item in list){
          PriceRule rule=PriceRule.fromJson(item);
          if(rule.handle==0){
            ruleStr="$ruleStr${rule.value}";
          }else{
            ruleStr="$ruleStr${rule.name}";
          }
        }
      }else{
        return rule;
      }

    }

    return ruleStr;
  }
  
   getParmValue(String id){
    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    return value;
   }

  void save(){
    bool result=true;
    for(PriceParm parm in widget.pricePart.childParmList){
      if(parm.handle==0&&parm.required==1){
        var value=getParmValue(parm.id);
        if(value.toString().isEmpty){
          ToastUtil.showToast("请输入${parm.name}");
          result=false;
          break;
        }
      }
    }
    if(!result){
      return;
    }


    var parm={
      "partId":widget.pricePart.id,
      "id":widget.priceMaterial.id,
      "data":values
    };


    BaseRequest.postHttp("price/materialitemedit",parameters: parm, canTip: true, context: context, onSuccess: (data){

      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshPart());
        eventBus.fire(EventRefreshBase());
      }
      Navigator.pop(context);
    }, onError: (error){

    });
  }

}
